clear;
clc;
numbits=[0,1,2,2,3,3,3,3,...
         4,4,4,4,4,4,4,4,...
         5,5,5,5,5,5,5,5,...
         5,5,5,5,5,5,5,5,...
         6,6,6,6,6,6,6,6,...
         6,6,6,6,6,6,6,6,...
         6,6,6,6,6,6,6,6,...
         6,6,6,6,6,6,6,6,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         7,7,7,7,7,7,7,7,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8,...
         8,8,8,8,8,8,8,8];
s=0:64:32767;
%y=wavread2('fspeech');
mulaw=zeros(1,length(s));

for k=1:length(s),
 mulaw(k)=code(s(k),numbits);
end

s2=log(1+255*abs(s/32768))/log(1+255);

mulaw;

figure(1), plot(s , bitxor(mulaw,255) , s , s2*128 + 128), grid
pause;
%decoding
s1=zeros(1,length(mulaw));

for n=1:length(mulaw),
s1(n)=encode(mulaw(n));
end

%--------------------------------------------------------------------------
% coding and decoding voice
s_code=wavread2('fspeech');

mulaw=zeros(1,length(s_code));

for l=1:length(s_code),
 mulaw(l)=code(s_code(l),numbits);
end

s_decode=zeros(length(mulaw),1);

for m=1:length(mulaw),
s_decode(m)=encode(mulaw(m));
end

figure(2), plot(s_code), grid
figure(3), plot(s_decode), grid
hist(s_code,100);
%---------------------------8 bit's code-----------------------------------
s_code8 = bitshift(s_code , -8);
%---------------------------8 bit's decode---------------------------------
s_decode8 = bitshift(s_code8 , +8);
figure(4), plot(s_decode8), grid
%--------------------------------------------------------------------------
Pe=sum((s_code - s_decode).^2)/length(s_code)
Pe8=sum((s_code - s_decode8).^2)/length(s_code)
Eabs=max(abs(s_code - s_decode))
Eabs8=max(abs(s_code - s_decode8))
%sound(s_deco/32768)
%wavwrite(s_decode/32768,8000,'laba1');